<?php

class MessagesForm extends CFormModel {

    public $users;
    public $message;

    public function attributeLabels() {
        return array (
            'message' => 'Текст сообщения',
            'users' => 'Пользователи',
        );
    }
    
    public function rules() {
        return array(
            array('users, message', 'required', 'message'=>'{attribute} не может быть пустым'),
        );
    }
    
    public function afterValidate() {
        if(!$this->hasErrors()) {
            $userArr = explode(',', $this->users);
            if(count($userArr)) {
                $userId = Yii::app()->user->getId();
                foreach ($userArr as $item) {
                    $sql = "SELECT * FROM `messages_dialogs` AS m WHERE m.user1Id IN ( $userId, $item ) AND m.user2Id IN ( $userId, $item )";
                    $dialog = Yii::app()->db->createCommand($sql)->query()->read();
                    
                    if(!$dialog) {
                        Yii::app()->db->createCommand()->insert('messages_dialogs', array(
                            'user1Id'=>$item, 'user2Id'=>Yii::app()->user->getId(), 'user1New'=>$item ));
                        $dialogId = Yii::app()->db->lastInsertID;
                    } else {
                        $dialogId = $dialog['dialogId'];
                    }
                    
                    Yii::app()->db->createCommand()->insert('messages', array(
                        'toId'=>$item, 'fromId'=>Yii::app()->user->getId(), 'sendDate'=>time(), 
                        'message'=>$this->message, 'dialogId'=>$dialogId
                    ));
                    
                    $messId = Yii::app()->db->lastInsertID;
                    if(!$dialog) {
                        Yii::app()->db->createCommand()->update('messages_dialogs', array('lastMessId'=>$messId), 'dialogId=:id', array(':id'=>$dialogId));
                    } else {
                        $field = $dialog['user1New'] && $dialog['user1New'] != $item ? 'user2New' : 'user1New';
                        $delField = $dialog['user1Del'] == $item ? 'user1Del' : 'user2Del';
                        Yii::app()->db->createCommand()->update('messages_dialogs', array('lastMessId'=>$messId, $field=>$item, $delField=>0), 'dialogId=:id', array(':id'=>$dialogId));
                    }
                }
            }
        }
    }
}